package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.query.EmployeeQueryForObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PermissionName;
import cn.wolfcode.crm.util.UploadUtil;
import com.alibaba.druid.util.StringUtils;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private ServletContext ctx;

    @RequiresPermissions("employee:index")
    @PermissionName("员工首页")
    @RequestMapping("index")
    public String index(){
        return "employee/list";
    }

    @RequestMapping("staff")
    public String staff(){
        return "employee/staff";
    }


    @RequestMapping("list")
    @ResponseBody
    @RequiresPermissions("employee:list")
    @PermissionName("员工数据")
    public PageResult list(EmployeeQueryForObject qo){
        return employeeService.query(qo);
    }

    //检查用户是否存在: true表示不存在, false 存在
    @RequiresPermissions("employee:validateUsername")
    @PermissionName("用户查询")
    @RequestMapping("validateUsername")
    @ResponseBody
    public boolean validateUsername(String username, Long id){
        //通过名称
        Employee employee = employeeService.checkName(username);
        if(id == null){
            return employee == null;
        }else{
            return true;
        }
    }


    @RequestMapping("save")
    @ResponseBody
    @RequiresPermissions("employee:save")
    @PermissionName("员工保存")
    public JsonResult save(Employee entity){
        JsonResult result = new JsonResult();
        try {
            employeeService.insert(entity);
        }catch (Exception e){
            e.printStackTrace();
            result = new JsonResult("保存操作失败");
        }
        return result;
    }


    @RequestMapping("update")
    @ResponseBody
    @RequiresPermissions("employee:update")
    @PermissionName("员工更新")
    public JsonResult update(Employee entity){
        JsonResult result = new JsonResult();
        try {
            employeeService.updateByPrimaryKey(entity);
        }catch (Exception e){
            e.printStackTrace();
            result = new JsonResult("编辑操作失败");
        }
        return result;
    }


    @RequestMapping("changeState")
    @ResponseBody
    @RequiresPermissions("employee:changeState")
    @PermissionName("员工状态")
    public JsonResult changeState(Long id){
        JsonResult result = new JsonResult();
        try {
            employeeService.changeState(id);
        }catch (Exception e){
            e.printStackTrace();
            result = new JsonResult("操作失败");
        }
        return result;
    }
    @RequestMapping("delete")
    @ResponseBody
    @RequiresPermissions("employee:delete")
    @PermissionName("员工删除")
    public JsonResult delete(Long id){
        JsonResult result = new JsonResult();
        try {
            employeeService.deleteByPrimaryKey(id);
        }catch (Exception e){
            e.printStackTrace();
            result = new JsonResult("操作失败");
        }
        return result;
    }
    @ResponseBody
    @RequestMapping("queryRoleByEmpId")
    public List<Long> queryRoleByEmpId(Long empId){

        return employeeService.queryRoleByEmpId(empId);
    }

    //根据部门ID查询该部门的所有员工(2018-7-12 ZHOU)
    @RequestMapping("queryEmployeeListByDepartmentId")
    @ResponseBody
    @RequiresPermissions("employee:queryEmployeeListByDepartmentId")
    @PermissionName("员工状态")
    public List<Employee> queryEmployeeListByDepartmentId(Long id){
        return employeeService.queryEmployeeListByDepartmentId(id);
    }

    @RequestMapping("resetPassword")
    @ResponseBody
    @RequiresPermissions("employee:resetPassword")
    @PermissionName("重置密码")
    public JsonResult resetPassword(Long id){
        JsonResult result = new JsonResult();
        try {
            employeeService.resetPassword(id);
        }catch (Exception e){
            e.printStackTrace();
            result = new JsonResult("操作失败");
        }
        return result;
    }

    @RequestMapping("importExcel")
    @ResponseBody
    public void importExcel(MultipartFile uploadFile) throws Exception {
        InputStream inputStream = uploadFile.getInputStream();
        //获取工作簿
        Workbook workbook = Workbook.getWorkbook(inputStream);
        //获取页签
        Sheet sheet = workbook.getSheet(0);
        //获取单元格
        Cell cell = sheet.getCell(3, 0);
        //获取内容列
        int rows = sheet.getRows();
        Employee employee = null;
        for (int i = 1; i < rows; i++) {
            employee=new Employee();
            cell = sheet.getCell(0, i);
            employee.setUsername(cell.getContents());
            cell = sheet.getCell(1, i);
            employee.setRealname(cell.getContents());
            cell = sheet.getCell(2, i);
            employee.setTel(cell.getContents());
            cell = sheet.getCell(3, i);
            employee.setEmail(cell.getContents());
            cell = sheet.getCell(4, i);
            String deptName = cell.getContents();
            Department department = departmentService.selectDepartmentByName(deptName);
            employee.setDept(department);
            cell = sheet.getCell(5, i);
            String inputTime = cell.getContents();
            if (!StringUtils.isEmpty(inputTime)){
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date date = simpleDateFormat.parse(inputTime);
                employee.setInputTime(date);
            }
            cell = sheet.getCell(6, i);
            String admin = cell.getContents();
            employee.setAdmin("是".equals(admin)?true:false);
            cell = sheet.getCell(7, i);
            String state = cell.getContents();
            employee.setState("在职".equals(state)?1:0);
            employeeService.insert(employee);
        }
        //关闭资源
        workbook.close();
    }
    @RequestMapping("queryHeadteacher")
    @ResponseBody
    public List<Employee> queryHeadteacher(){


        return  employeeService.queryHeadteacher();
    }

    @RequestMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception{
        //导出
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String fileName = sdf.format(new Date()) + ".xls";
        response.setContentType("application/x-excel");
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename="
                + fileName);
        List<Employee> list = new ArrayList<>();
        List<Employee> employees = employeeService.selectAll();
        for (Employee employee : employees) {
            list.add(employee);
        }
        //1.创建工作薄
        WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());
        //2.创建页签
        WritableSheet sheet = workbook.createSheet("员工列表", 0);
        //3.创建单元格
        String[] header = new String[]{"账号","姓名","电话","邮箱","部门","入职时间","超级管理员","状态"};
        Label label = null;
        for (int i = 0; i < header.length; i++) {
            label = new Label(i,0,header[i]);
            //4.添加到页签中
            sheet.addCell(label);
        }
        //迭代数据
        for (int i = 1; i <list.size()+1 ; i++) {
            label = new Label(0,i,list.get(i-1).getUsername());
            sheet.addCell(label);
            label = new Label(1,i,list.get(i-1).getRealname());
            sheet.addCell(label);
            label = new Label(2,i,list.get(i-1).getTel());
            sheet.addCell(label);
            label = new Label(3,i,list.get(i-1).getEmail());
            sheet.addCell(label);
            if(list.get(i-1).getDept()!=null) {
                label = new Label(4, i, list.get(i - 1).getDept().getName());
            }else{
                label = new Label(4, i, "");
            }
            sheet.addCell(label);
            if (list.get(i-1).getInputTime()==null){
                label = new Label(5, i, "");
                sheet.addCell(label);
            }else{
                sdf = new SimpleDateFormat("yyyy-MM-dd");
                String newdate = sdf.format(list.get(i-1).getInputTime());
                label = new Label(5, i, newdate);
                sheet.addCell(label);
            }
            label = new Label(6,i,list.get(i-1).isAdmin()?"是":"否");
            sheet.addCell(label);
            label = new Label(7,i,list.get(i-1).getState()==1?"在职":"离职");
            sheet.addCell(label);
        }
        //5.写出数据
        workbook.write();
        workbook.close();
    }
    //查所有员工的基本信息，用来营销人员下拉框
    @ResponseBody
    @RequestMapping("selectAll")
    public List<Employee> selectAll(){
        return employeeService.selectAll();
    }
    //图片上传
    @RequestMapping("uploadPic")
    @ResponseBody
    public JsonResult uploadPic(MultipartFile pic,Long empId){
//使用工具来类进行保存
        //获得当前项目的真实路径
        //当图片不为空的时候
        Employee employee = employeeService.queryPicUrlByEmpId(empId);
        if (pic!=null) {
            //当image不为空时
            if (employee.getImagePath()!=null) {
                //删除当前的保存的图片
                UploadUtil.deleteFile(ctx, employee.getImagePath());
                //删除数据库中保存的imagePath
            }
            String imagePath = UploadUtil.upload(pic, ctx.getRealPath("/upload"));
            employee.setImagePath(imagePath);
        }
        JsonResult result = new JsonResult();
        //获取品牌名字保存到商品中

        try {
            employeeService.saveImageUrl(employee);
        } catch (Exception e) {
       result = new JsonResult("上传失败");
            e.printStackTrace();
        }
        return result;
    }
    /*回显图片*/
    @ResponseBody
    @RequestMapping("queryPicByEmpId")
    public Employee queryPicByEmpId(Long empId){

        return employeeService.queryPicUrlByEmpId(empId) ;
    }



}